// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
// 华容道游戏脚本
cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
		cell_hor_count:4,
		cell_ver_count:5,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
		//将所有子节点读出
		this.chess = this.node.children.slice();
		this.chess.pop();//弹出最后一个
		this.goalChess = this.chess[0];
		this.table =null;
		
	},
	update(dt){
		if (this.table==null){
			//初始化桌面
			this.table = [];
			this.cell_width = this.node.width/this.cell_hor_count;
			this.cell_height = this.node.height/this.cell_ver_count;
			for (let i = -1;i<=this.cell_hor_count;i++){
				this.table[i] = [];
				for(let j = -1 ; j<=this.cell_ver_count;j++){
					if (i<0||j<0||i==this.cell_hor_count||j==this.cell_ver_count){
						this.table[i][j] = -2; // 边界限制
						continue
					}
					let nowcheck;
					nowcheck = cc.p(this.cell_width*i+this.cell_width/2,this.cell_height*j+this.cell_height/2);
					this.table[i][j] = -1; //空白标志
					for (let w = 0;w<this.chess.length;w++){
						if (this.regionHasPoint(this.chess[w].getPosition(),this.cell_width/2,this.cell_height/2,nowcheck)){
							this.table[i][j] = w;
							this.chess[w].chess_tag = w;
							this.chess[w].table=this.table;
							this.chess[w].cell_width = this.cell_width;
							this.chess[w].cell_height = this.cell_height;
							break;
						}
					}
				}
			}
		}
	},
	regionHasPoint:function(center,width_2,height_2,point){
		if((point.x<center.x-width_2)||(point.x>center.x+width_2))
			return false;
		if((point.y<center.y-height_2)||(point.y>center.y+height_2))
			return false;
		return true;
	},
	
    start () {
		
    },

    // update (dt) {},
});
